package com.atguigu.guli.service.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.atguigu.guli.service.oss.service.FileService;
import com.atguigu.guli.service.oss.unil.OssProperties;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    OssProperties ossProperties;

    @Override
    public String upload(InputStream inputStream, String module, String oFilename) {
        String bucketName = ossProperties.getBucketName();
        String endpoint = ossProperties.getEndpoint();
        String keyId = ossProperties.getKeyId();
        String keySecret = ossProperties.getKeySecret();
        OSS build = new OSSClientBuilder().build(endpoint, keyId, keySecret);
        if (!build.doesBucketExist(bucketName)){
            build.createBucket(bucketName);
            build.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
        }
        String folder = new DateTime().toString("yyyy/MM/dd");
        String fileName = UUID.randomUUID().toString();
        String fileExtension = oFilename.substring(oFilename.lastIndexOf('.'));
        String key = module + "/" + folder + "/" + fileName + fileExtension;
        build.putObject(ossProperties.getBucketName(),key,inputStream);
        build.shutdown();
        String substring = endpoint.substring(endpoint.lastIndexOf('/')+1);
        return "https://"+bucketName+"."+substring+"/"+key;
    }

    @Override
    public void removeFile(String url) {
        String bucketName = ossProperties.getBucketName();
        String endpoint = ossProperties.getEndpoint();
        String keyId = ossProperties.getKeyId();
        String keySecret = ossProperties.getKeySecret();
        OSS build = new OSSClientBuilder().build(endpoint, keyId, keySecret);
        System.out.println(url);
        String hosts = "https://"+bucketName+"."+endpoint.substring(endpoint.lastIndexOf("/")+1)+"/";
        String objName = url.substring(hosts.length());
        build.deleteObject(bucketName,objName);
        build.shutdown();
        System.out.println("文件删除!");
    }
}
